<template>
  <PageWrapper title="" contentFullHeight fixedHeight :loading="loading">
    <div class="bg-white h-full p-4">
      <div class="flex justify-end gap-10px mb-2">
        <a-button type="primary" @click="handleCreate">新增</a-button>
        <a-button type="primary" @click="handleSubmit">保存</a-button>
        <a-button type="primary" @click="handleRun">运行</a-button>
        <a-button type="danger" @click="handleDelete">删除</a-button>
      </div>
      <Scrollbar>
        <div v-if="queryId">
          <splitpanes class="default-theme" style="height: calc(100vh - 200px)">
            <pane size="70">
              <splitpanes horizontal>
                <pane>
                  <FieldTable
                    :formGetFieldsData="formGetFieldsData"
                    v-model:modelValue="dataRef.fieldsSelected"
                  />
                </pane>
                <pane>
                  <FieldForm
                    :fieldsSelected="dataRef.fieldsSelected"
                    :queryId="queryId"
                    :formCode="dataRef.formCode"
                    ref="fieldFormRef"
                  />
                </pane>
              </splitpanes>
            </pane>
            <pane>
              <FieldEdit
                ref="fieldEditRef"
                :fieldEditData="fieldEditData"
                @change-form-code="handleChangeFormCode"
              />
            </pane>
          </splitpanes>
        </div>
      </Scrollbar>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, onMounted, h } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { Scrollbar } from '/@/components/Scrollbar';
  import { Splitpanes, Pane } from 'splitpanes';
  import 'splitpanes/dist/splitpanes.css';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { useRouter } from 'vue-router';
  import FieldTable from './fieldTable/index.vue';
  import FieldEdit from './fieldEdit/index.vue';
  import FieldForm from './fieldForm/index.vue';
  import {
    getQueryDesignerEditPage,
    getQueryCreateNew,
    getQueryDel,
    getQueryUpdate,
  } from '/@/api/reportForms/reportForms';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGo } from '/@/hooks/web/usePage';
  const { createMessage, createConfirm } = useMessage();
  const { currentRoute, replace } = useRouter();
  const { setTitle, close } = useTabs();
  const loading = ref(false);
  const currentQuery = ref<any>({});
  const dataRef = ref<Recordable>({});
  const fieldEditRef = ref<any>(null);
  const fieldEditData = ref<Recordable>({}); //左侧数据
  const fieldFormRef = ref<any>(null);
  const queryId = ref('');
  const fetch = async () => {
    if (currentQuery.value.id) {
      queryId.value = currentQuery.value.id;
      const res = await getQueryDesignerEditPage({ id: currentQuery.value.id });
      dataRef.value = res;
      await getFormGetFieldsDataTo();
      fieldEditData.value = {
        flowStatus: dataRef.value.flowStatus,
        formCode: dataRef.value.formCode,
        order: dataRef.value.order,
        queryName: dataRef.value.queryName,
        queryRelated: dataRef.value.queryRelated,
        stateDesc: dataRef.value.stateDesc,
        beginDate: dataRef.value.beginDate,
        endDate: dataRef.value.endDate,
      };
      if (
        !fieldEditData.value.order ||
        (fieldEditData.value.order && fieldEditData.value.order.length == 0)
      ) {
        fieldEditData.value.order = formGetFieldsData.value;
      } else {
        const oredrs = {};
        fieldEditData.value.order.forEach((item) => {
          oredrs[item.fieldName] = item.sort;
        });
        const newFormGetFieldsData = [...formGetFieldsData.value];
        newFormGetFieldsData.forEach((item) => {
          if (Reflect.has(oredrs, item.name)) {
            item['orderFieldCode'] = oredrs[item.name];
          }
        });
        fieldEditData.value.order = [...newFormGetFieldsData];
      }
      console.log('formGetFieldsData.value', formGetFieldsData.value);
      console.log('fieldEditData.value', fieldEditData.value);
    }
  };

  //点击数据表返回formCode
  const handleChangeFormCode = async (val) => {
    dataRef.value.formCode = val;
    await getFormGetFieldsDataTo();
    fieldEditData.value.order = formGetFieldsData.value;
  };

  const formGetFieldsData = ref<Recordable[]>([]);
  //获取目标字段
  const getFormGetFieldsDataTo = async () => {
    try {
      if (dataRef.value?.formCode) {
        await getFormGetFields({ formCode: dataRef.value.formCode }).then((res) => {
          formGetFieldsData.value = res || [];
          if (isArray(formGetFieldsData.value)) {
            formGetFieldsData.value.forEach((item) => {
              item.label = item.title;
              item.value = item.name;
              delete item.options;
            });
          }
        });
      }
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };
  onMounted(() => {
    currentQuery.value = currentRoute.value.query;
    console.log('currentRoute.value', currentRoute.value);
    // setTitle(currentRoute.value.meta.title as string);
    fetch();
  });
  //新增
  const handleCreate = () => {
    loading.value = true;
    getQueryCreateNew().then((res) => {
      loading.value = false;
      console.log('res', res);
      // updatePath(currentRoute.value.path + '?id=' + res.id);
      close(currentRoute.value);
      replace({
        path: currentRoute.value.path,
        query: {
          id: res.id,
        },
      });
    });
  };
  //保存
  const handleSubmit = async () => {
    console.log('fieldEditRef', fieldEditRef.value);
    const params = {
      ...fieldEditRef.value.dataRef,
      fieldForm: fieldFormRef.value.dataRef,
      fieldsSelected: dataRef.value.fieldsSelected,
      id: currentQuery.value.id,
    };
    console.log('params', params);
    await getQueryUpdate(params);
    createMessage.success('操作成功');
  };

  const go = useGo();
  //运行
  const handleRun = () => {
    go({
      path: '/searchTableNormal',
      query: {
        id: queryId.value,
        title: fieldEditRef.value.dataRef.queryName,
        cacheName: `searchTableNormal${queryId.value}`,
      },
    });
  };
  //删除
  const handleDelete = () => {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '确定删除吗？'),
      onOk: async () => {
        try {
          loading.value = true;
          await getQueryDel({ ids: queryId.value });
          createMessage.success('删除成功');
          loading.value = false;
          close(currentRoute.value);
          replace({
            path: currentRoute.value.path,
          });
        } catch (error) {}
      },
    });
  };
</script>
<style lang="less" scoped>
  .splitpanes__pane {
    background-color: transparent !important;
  }
</style>
